# @Version        : 1.0
# @Update Time    : 2025/3/13 14:32
# @File           : home_view.py
# @IDE            : PyCharm
# @Desc           : 文件描述信息

# views/home_view.py
import flet as ft
from flet_core import ImageFit

from components.carousel import Carousel
from services.product_service import ProductService  # 引入 ProductService


class HomeView(ft.ListView):
    def __init__(self, page: ft.Page, params: dict = None):
        super().__init__()
        self.page = page
        self.params = params
        self.expand = True
        self.spacing = 20
        self.padding = ft.padding.only(bottom=80)  # 底部留出导航栏空间
        self.discount_card = None  # 添加 discount_card 属性
        self.product_service = ProductService()  # 初始化 ProductService
        self.build_ui()

    def build_ui(self):
        # 顶部用户信息区
        header = ft.Row(
            controls=[
                # 🧩 用户头像
                ft.CircleAvatar(
                    radius=28,
                    content=ft.Image(src="assets/avatar.png")  # 默认头像
                ),
                ft.Column(
                    [
                        ft.Text("*先生的主页", size=18, weight=ft.FontWeight.BOLD),
                        ft.Text("你好，朱**", color=ft.colors.GREY_600),
                        ft.Text(
                            "找到你想要的新鲜食材",
                            size=12, color=ft.colors.GREY_500
                        )
                    ], spacing=2
                ),
                ft.Container(expand=True)  # 右侧占位
            ],
            alignment=ft.MainAxisAlignment.START,
            vertical_alignment=ft.CrossAxisAlignment.CENTER
        )

        # 新会员优惠卡
        self.discount_card = ft.Container(
            image_src="assets/carousel.png",
            image_fit=ImageFit.COVER,
            # 设置背景图覆盖
            content=ft.Row(
                [
                    ft.Column(
                        [
                            ft.Row(
                                [
                                    ft.Text("新会员", size=16),
                                    ft.Container(
                                        content=ft.Text(
                                            "40%",
                                            color=ft.colors.WHITE,
                                            weight=ft.FontWeight.BOLD
                                        ),
                                        padding=ft.padding.symmetric(horizontal=12, vertical=4),
                                        bgcolor=ft.colors.GREEN_800,
                                        border_radius=8
                                    )
                                ], spacing=8
                            ),
                            ft.Text("我们", size=24, weight=ft.FontWeight.BOLD),
                            ft.FilledButton(
                                "查看详情",
                                icon=ft.icons.ARROW_FORWARD,
                                style=ft.ButtonStyle(
                                    bgcolor=ft.colors.GREEN_800,
                                    shape=ft.RoundedRectangleBorder(radius=8)
                                )
                            )
                        ], spacing=12
                    ),
                ],
                alignment=ft.MainAxisAlignment.SPACE_BETWEEN,
                vertical_alignment=ft.CrossAxisAlignment.CENTER
            ),
            padding=20,
            bgcolor=ft.colors.GREEN_100,
            border_radius=16
        )

        # 分类导航
        categories = ft.Column(
            [
                ft.Row(
                    [
                        ft.Text("分类", size=16, weight=ft.FontWeight.BOLD),
                        # 点击查看分类跳转 /category
                        ft.TextButton(
                            "查看全部",
                            icon=ft.icons.CHEVRON_RIGHT,
                            style=ft.ButtonStyle(padding=0),
                            on_click=lambda _: self.page.go("/category")
                        )
                    ], alignment=ft.MainAxisAlignment.SPACE_BETWEEN
                ),
                ft.GridView(
                    controls=[
                        self._build_category_item(ft.icons.APPLE, "水果"),
                        self._build_category_item(ft.icons.GRASS, "蔬菜"),
                        self._build_category_item(ft.icons.BAKERY_DINING, "面包"),
                        self._build_category_item(ft.icons.SET_MEAL, "肉")
                    ],
                    runs_count=4,
                    spacing=10,
                    run_spacing=20,
                    max_extent=80  # 控制每项宽度
                )
            ], spacing=15
        )

        # 热门商品区（与分类导航同级）
        hot_products = ft.Column(
            [
                ft.Row(
                    [
                        ft.Text("热门商品", size=16, weight=ft.FontWeight.BOLD),
                        ft.TextButton(
                            "查看全部",
                            icon=ft.icons.CHEVRON_RIGHT,
                            style=ft.ButtonStyle(padding=0)
                        )
                    ], alignment=ft.MainAxisAlignment.SPACE_BETWEEN
                ),
                ft.GridView(
                    runs_count=2,
                    controls=self._build_product_items(),  # 使用服务获取商品数据
                    spacing=15,
                    run_spacing=20,
                    max_extent=200  # 控制商品卡片宽度
                )
            ], spacing=15
        )

        self.controls = [
            header,
            ft.Row(
                controls=[
                    ft.TextField(
                        hint_text="搜索新鲜食材",
                        border_radius=20,
                        bgcolor=ft.colors.GREEN_100,
                        border_color=ft.colors.TRANSPARENT,
                        prefix_icon=ft.icons.SEARCH,
                        height=45,
                        expand=True
                    ),
                    ft.IconButton(
                        icon=ft.icons.SEARCH,
                        icon_color=ft.colors.GREEN_800,  # 设置搜索图标的颜色
                        on_click=lambda _: print("搜索按钮点击事件")
                    )
                ],
                alignment=ft.MainAxisAlignment.START
            ),
            self.discount_card,
            categories,
            hot_products  # 热门商品区
        ]

    def _build_product_items(self):
        products = self.product_service.get_hot_products()  # 获取热门商品数据
        return [
            self._build_product_item(product["id"], product["image"], product["title"], product["price"])
            for product in products
        ]

    def _build_product_item(self, data_id, image, title, price):
        return ft.Container(
            height=180,  # 固定高度
            width=160,  # 固定宽度
            content=ft.Column(
                [
                    ft.Image(src=image, height=120, fit=ft.ImageFit.COVER),
                    ft.Text(title, size=14, weight=ft.FontWeight.BOLD),
                    ft.Text(price, color=ft.colors.GREEN_800)
                ], spacing=5
            ),
            bgcolor=ft.colors.GREY_100,
            border_radius=12,
            padding=10,
            on_click=lambda e: self.page.go(f"/product_detail?data_id={data_id}")
        )

    def _build_category_item(self, icon, text):
        return ft.Container(
            content=ft.Column(
                [
                    ft.Icon(icon, size=28, color=ft.colors.GREEN_800),
                    ft.Text(text, size=14, color=ft.colors.GREY_700)
                ],
                spacing=8,
                horizontal_alignment=ft.CrossAxisAlignment.CENTER
            ),
            padding=10,
            bgcolor=ft.colors.GREY_100,
            border_radius=12,
            on_click=lambda e: print(f"进入{text}分类")
        )

    def on_route_change(self, route):
        if self.page.route != "/":
            self.discount_card.stop_carousel()  # 停止轮播图
